package com.dayu.finecomm.protocol.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.protocol.ProtocolPacket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @ClassName: ProtocolLogger
 * @Description:报文打印
 * @author: 戴卫国
 * @date: 2018年4月4日 上午11:21:55
 * 
 * @Copyright: 2018 dayu Inc. All rights reserved.
 */
public class ProtocolLogger extends ChannelInboundHandlerAdapter {

	boolean validPacket;

	Logger LOGGER = LoggerFactory.getLogger(getClass());

	private static final char[] TBL = new char[256 * 4];

	static {

		final char[] DIGITS = "0123456789ABCDEF".toCharArray();

		for (int i = 0; i < 256; i++) {
			TBL[i << 1] = DIGITS[i >>> 4 & 0x0F];
			TBL[(i << 1) + 1] = DIGITS[i & 0x0F];
		}
	}

	public ProtocolLogger(boolean validPacket) {
		this.validPacket = validPacket;
	}

	public ProtocolLogger() {
		this(true);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		ByteBuf b = null;

		if (!(msg instanceof ProtocolPacket)) {
			ctx.fireChannelRead(msg);
			return;
		}

		ProtocolPacket pack = ((ProtocolPacket) msg);

		if (pack.supported != this.validPacket) {
			ctx.fireChannelRead(msg);
			return;
		}

		b = ((ProtocolPacket) msg).packet.slice();

		if (b != null) {

			StringBuffer sb = new StringBuffer(b.readableBytes() * 3);

			while (b.isReadable()) {

				int i = b.readUnsignedByte() << 1;
				sb.append(TBL[i]).append(TBL[i + 1]);
				sb.append(" ");
			}

			LOGGER.info(sb.toString());
		}

		ctx.fireChannelRead(msg);
	}
}
